import requests
import json
from bs4 import BeautifulSoup


# base_url = "https://www.sigmaaldrich.cn"
# 商品详情base_url
product_url = "https://www.sigmaaldrich.cn/CN/zh/product/mm"

headers = {
    "accept": "*/*",
    "accept-language": "zh-CN,zh;q=0.9",
    "cache-control": "no-cache",
    "content-type": "application/json",
    "origin": "https://www.sigmaaldrich.cn",
    "pragma": "no-cache",
    "priority": "u=1, i",
    "referer": "https://www.sigmaaldrich.cn/CN/zh",
    "sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"macOS"',
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
    "x-gql-access-token": "8b93e061-70d3-11f0-aab6-dd550d926ee3",
    "x-gql-blue-erp-enabled": "true",
    "x-gql-country": "CN",
    "x-gql-language": "zh",
    "x-gql-operation-name": "SearchSuggestions",
    "x-gql-requesting-website": "SigmaAldrich",
    "x-gql-store": "sial",
    "x-gql-user-erp-type": "ANONYMOUS",
}


def search_product(product_code):
    url = "https://www.sigmaaldrich.cn/api"
    params = {"operation": "SearchSuggestions"}
    data = {
        "operationName": "SearchSuggestions",
        "variables": {
            "input": {
                "term": product_code,
                "types": [
                    "PRODUCT_NAME",
                    "PRODUCT_NUMBER",
                    "CAS_NUMBER",
                    "CATEGORY",
                    "PINYIN",
                ],
                "filter": "erp_type:all",
            }
        },
        "query": "query SearchSuggestions($input: GetSearchSuggestionsInput!) {\n  getSearchSuggestions(input: $input) {\n    count\n    suggestions {\n      productName {\n        ...Suggestion\n        __typename\n      }\n      casNumber {\n        ...Suggestion\n        __typename\n      }\n      materialNumber {\n        ...Suggestion\n        __typename\n      }\n      productNumber {\n        ...Suggestion\n        __typename\n      }\n      relatedCategories {\n        value\n        facetId\n        __typename\n      }\n      pinyin {\n        ...Suggestion\n        __typename\n      }\n      __typename\n    }\n    __typename\n  }\n}\n\nfragment Suggestion on Suggestion {\n  label\n  brandKey\n  productKey\n  substanceKey\n  __typename\n}",
    }
    data = json.dumps(data, separators=(",", ":"))
    response = requests.post(url, headers=headers, params=params, data=data)
    # print(response.json())
    product_list = (
        response.json()["data"]
        .get("getSearchSuggestions", {})
        .get("suggestions", {})
        .get("productNumber", [])
    )
    if product_list:
        print(product_list)
        return product_list[0].get("label")
    return None


def get_product_detail(product_code) -> BeautifulSoup | None:
    url = f"{product_url}/{product_code}"
    response = requests.get(url, headers=headers)
    if response.status_code != 200:
        return None
    soup = BeautifulSoup(response.text, "html.parser")
    return soup


def get_product_image_list(soup) -> list[str]:
    img_list = []
    temp_dom = soup.find(
        "div", class_="MuiGrid-root jss137 MuiGrid-container MuiGrid-wrap-xs-nowrap"
    )
    if temp_dom.find("img"):
        for img_dom in temp_dom.find_all("img"):
            img_list.append("https://www.sigmaaldrich.cn" + img_dom.get("src"))
        return img_list
    return None


# def process_img_list(product_code):
#     if new_code := search_product(product_code):
#         if soup := get_product_detail(new_code):
#             if temp_list := get_product_image_list(soup):
#                 img_list = [{"photo": img} for img in temp_list]

#                 img_list = img_list[:5]  # 确保最多5个元素
#                 img_list += [img_list[-1]] * (5 - len(img_list))  # 用最后一项补足5个


#                 return img_list
#     return None
def process_img_list(product_code):
    if soup := get_product_detail(product_code):
        if temp_list := get_product_image_list(soup):
            img_list = [{"photo": img} for img in temp_list]

            img_list = img_list[:5]  # 确保最多5个元素
            img_list += [img_list[-1]] * (5 - len(img_list))  # 用最后一项补足5个

            return img_list
    return None


if __name__ == "__main__":
    res = process_img_list("UFC5050")
    print(res)
